package logic

import (
	"context"
	"github.com/jinzhu/copier"
	"my-zero-tiktok/apps/message/models"
	"my-zero-tiktok/common/xerr"

	"my-zero-tiktok/apps/message/pb/pb"
	"my-zero-tiktok/apps/message/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetMessageListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetMessageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMessageListLogic {
	return &GetMessageListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// GetMessageList 消息列表/聊天列表
func (l *GetMessageListLogic) GetMessageList(in *pb.GetListRequest) (*pb.GetListResponse, error) {
	var (
		messages []*models.Message
		err      error
	)

	switch in.ToId {
	case 0:
		messages, err = l.svcCtx.MessageModel.FindListByFromID(l.ctx, in.FromId)
	default:
		messages, err = l.svcCtx.MessageModel.FindListByChat(l.ctx, in.FromId, in.ToId)
	}
	if err != nil {
		return nil, xerr.New(xerr.MessageGetListError)
	}

	list := make([]*pb.Message, len(messages))
	for i, item := range messages {
		var msg pb.Message
		_ = copier.Copy(&msg, item)
		list[i] = &msg
	}
	return &pb.GetListResponse{List: list}, nil
}
